﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;

namespace DesignParttenSamples
{

    // TimerCallback: public delegate void TimeCallback(object state)
    // 说明：委托是对具体方法的抽象，它屏蔽了委托的调用者与实际执行方法间的关联关系。

    public class AsyncInvoker
    {
        public AsyncInvoker()
        {
            new Timer(new TimerCallback(OnTimerInterval), "slow", 2500, 2500);
            new Timer(new TimerCallback(OnTimerInterval), "fast", 2000, 2000);
            Trace.WriteLine("Method");

        }
        static void OnTimerInterval(object state)
        {
            Trace.WriteLine(state as string);
        }

        
    }

    public delegate void StringAssignmentEventHandler();

    public class InvokeList
    {
        List<StringAssignmentEventHandler> handlers;
        string[] message = new string[3];

        //public InvokeList()
        //{
        //    handlers = new List<StringAssignmentEventHandler>
        //    {
        //        AppendHello,
        //        AppendComma,
        //        AppendWorld
        //    };

        //}

        public InvokeList()
        {

            StringAssignmentEventHandler handler = null;
            handler += new StringAssignmentEventHandler(AppendHello);
            handler += new StringAssignmentEventHandler(AppendComma);
            handler += new StringAssignmentEventHandler(AppendWorld);
            handler.Invoke();

        }

        //public void Invoke()
        //{
        //    handlers.ForEach(x => x());
        //}

        public string this[int index]
        {
            get { return message[index]; }
        }

        public void AppendHello()
        {
            message[0] = "Hello";
        }

        public void AppendComma()
        {
            message[1] = ",";
        }

        public void AppendWorld()
        {
            message[2] = "world!";
        }
    }

    public class AnnoymousInvokeList
    {
        string[] message = new string[3];
        public AnnoymousInvokeList()
        {
            StringAssignmentEventHandler handler = null;
            handler += delegate{ message[0] = "Hello"; };
            handler+=()=> { message[1] = ","; };
            handler += () => { message[2] = "world!"; };
            handler.Invoke();
        }

        public string this[int index]
        {
            get { return message[index]; }
        }

    }
}
